package cn.ztydata.teachingsystem.heaven.service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * Created by Administrator on 2014/12/18.
 */
@Service
public class SessionService {
    private final static Logger log = LoggerFactory.getLogger(SessionService.class);

    @Autowired
    private RedisTemplate redisTemplate;

    @Value("${session.KeyPrefix}")
    private String sessionPrefix;

    @Value("${session.MaxInactiveInterval}")
    private int MaxInactiveInterval;

    /**
     * 获取持久层中对应的会话数据
     * @param sessionId     会话id
     * @return
     */
    public Map<String, Object> getData(String sessionId){

        ValueOperations<String, Map<String, Object>> valueOps = redisTemplate.opsForValue();
        Map<String, Object> result = valueOps.get(this.sessionPrefix + sessionId);

        if(result != null) {
            log.debug("get session data:result != null");

            //更新对应会话的有效期
            this.updateTTL(sessionId);
        }

        log.debug("return session data");

        return result;
    }

    /**
     * 把指定数据存入持久层
     * @param sessionId     会话id
     * @param data          会话数据
     */
    public void saveData(String sessionId, Map<String, Object> data){
        ValueOperations<String, Map<String, Object>> valueOps = redisTemplate.opsForValue();

        log.debug("save session data");

        valueOps.set(this.sessionPrefix + sessionId, data, this.MaxInactiveInterval, TimeUnit.SECONDS);
    }

    /**
     * 更新指定会话时间
     * @param sessionId     会话id
     */
    public void updateTTL(String sessionId){
        log.debug("update session ttl by sessionId");

        redisTemplate.expire(this.sessionPrefix + sessionId, this.MaxInactiveInterval, TimeUnit.SECONDS);
    }

    /**
     * 获取指定会话的剩余有效期（毫秒）
     * @param sessionId     会话id
     * @return
     */
    public long getTTL(String sessionId){
        log.debug("return session ttl by sessionId");

        return redisTemplate.getExpire(this.sessionPrefix + sessionId, TimeUnit.DAYS.MILLISECONDS);
    }
}
